import { Component, OnInit, Input, SimpleChanges, OnChanges } from '@angular/core';
import { TurbStatus } from "../../../../entity/turbstatus.model";
import { TurbStatusService } from "../../../../service/turbstatus.service";
import { FarmService } from "../../../../service/farm.service";
import { Farm } from "../../../../entity/farm.model";
import { List } from "linqts";
import { ApplicationService } from "../../../../service/application.service";
import { Router } from '@angular/router';

import {
  trigger, // 动画封装触发，外部的触发器
  state, // 转场状态控制
  style, // 用来书写基本的样式
  transition, // 用来实现css3的 transition
  animate, // 用来实现css3的animations
  keyframes // 用来实现css3 keyframes的
} from '@angular/animations';
import { fadeIn } from '../../../../../platform/zknwui/core/common/animation/fadeIn-animation';


@Component({
  selector: 'app-turbstatus-panel',
  templateUrl: './turbstatus-panel.component.html',
  styleUrls: ['./turbstatus-panel.component.css'],
  animations: [fadeIn]
})
export class TurbstatusPanelComponent implements OnInit, OnChanges {
  /**
   * echarts实例对象
   * 
   * @private
   * @type {*}@memberof RealtimePowerPanelComponent
   */
  private echartsIntance: any;

  public option: object;

  public windShow: boolean = false;

  /**
   * 风机状态统计
   * 
   * @type {TurbstatusData[]}@memberof TurbstatusPanelComponent
   */
  @Input()
  totalTurbstatusDatas: TurbstatusData[];
  /**
  * 风机状态统计明细
  * 
  * @type {TurbstatusData[]}@memberof TurbstatusPanelComponent
  */
  @Input()
  turbstatusTable: TurbstatusTable;
  /**
   * turbstatus弹窗标题
   * 
   * @type {string}
   * @memberof TurbstatusPanelComponent
   */
  @Input()
  title: string = "风机状态";
  @Input()
  orient:string="vertical";
  private a = 3;


  private color: string[];

  private datas: NameValue[] = [];
  private legendData: string[] = ['发电', '离线', '待机', '故障', '检修'];
  public url: string;
  // 注入服务
  constructor(
    private application: ApplicationService,
    private router:Router
  ) {



  }

  ngOnInit() {
    if (this.title == "风机状态") {
      this.url = "status.png";
    } else {
      this.url = "Inverter2.png";
    }
  }
  ngOnChanges(changes: SimpleChanges) {
    if (changes['totalTurbstatusDatas'] && changes['totalTurbstatusDatas'].currentValue) {
      this.legendData = this.totalTurbstatusDatas.map(data => data.name);
      this.changeData();



    }
  }
  private changeData() {
    this.initOption();
  }
  private initOption() {

    const index = this.application.currentUserFarms.findIndex(farm => farm.farmCategory === "photovoltaic");
    let centerArg: string = "25%";
    let legendTop: string = "50%";
    
    if (index === -1) {
      //没有光伏
      centerArg = "40%";
      legendTop = "80%";  
    }
    if ((this.totalTurbstatusDatas != null || this.totalTurbstatusDatas.length > 0) && this.option == null) {

      this.color = this.totalTurbstatusDatas.map(o => o.color);
      this.totalTurbstatusDatas.forEach(element => {
        this.datas.push({ name: element.name, value: parseInt(element.value.toFixed(2)) })
      })


      this.option = {
        tooltip: {
          trigger: 'item',
          formatter: "{b}: {c} ({d}%)"
        },
        color: this.color,
        legend: { //图例组件，颜色和名字
          orient: this.orient,
          top: legendTop,
          bottom: 0,
          itemGap: 8, //图例每项之间的间隔
          itemWidth: 8,
          itemHeight: 8,
          // type: "scroll",
          // icon: 'rect',
          data: this.legendData,
          formatter: (legend) => {
            return legend + '(' + this.datas.find(o => o.name == legend).value + ' )';
          },
          textStyle: {
            color: [],
            fontStyle: 'normal',
            fontFamily: '微软雅黑',
            fontSize: 12,
          }
        },
        grid: {
          left: 0,
          right: 0,
          top: 0,
          bottom: 0,
          containLabel: true
        },
        series: [{
          name: '',
          type: 'pie',
          clockwise: false, //饼图的扇区是否是顺时针排布
          minAngle: 20, //最小的扇区角度（0 ~ 360）
          center: ['50%', centerArg], //饼图的中心（圆心）坐标
          radius: ['52%', '78%'], //饼图的半径,可以具体数值，也可以百分比
          avoidLabelOverlap: true, ////是否启用防止标签重叠
          itemStyle: { //图形样式
            normal: {
              borderColor: '#1e2239',
              borderWidth: 1.5,
            },
          },
          label: { //标签的位置
            normal: {
              show: true,
              position: 'inside', //标签的位置
              formatter: "{c}",
              textStyle: {
                color: '#fff',
              }
            },
            emphasis: {
              show: true,
              textStyle: {
                fontWeight: 'bold'
              }
            }
          },
          data: this.datas.sort(function (a, b) { return a.value - b.value; }),
        }, {
          name: '',
          type: 'pie',
          clockwise: false,
          silent: true,
          minAngle: 20, //最小的扇区角度（0 ~ 360）
          center: ['50%', centerArg], //饼图的中心（圆心）坐标
          radius: [0, '53%'], //饼图的半径
          itemStyle: { //图形样式
            normal: {
              borderColor: '#1e2239',
              borderWidth: 1.5,
              opacity: 0.21,
            }
          },
          label: { //标签的位置
            normal: {
              show: false,
            }
          },
          data: this.datas.sort(function (a, b) { return a.value - b.value; }),
        }]
      };


    }
  }

  updateEchart() {
    if (this.echartsIntance != null) {
      this.datas.splice(0, this.datas.length);
      this.totalTurbstatusDatas.forEach(element => {
        this.datas.push({ name: element.name, value: parseInt(element.value.toFixed(2)) })
      })
      // console.log(this.turbstatusTable)
      this.echartsIntance.setOption(this.option);
    }
  }
  /**
     * 初始化echarts实例
     * 
     * 
     * @memberof Echart2Component
     */
  onChartInit(ec: any) {
    this.echartsIntance = ec;
  }
  enterPower() {
    this.windShow = true;
  }
  leavePower() {
    this.windShow = false;
  }
  ondblclick(ev) {
    if (this.title == "风机状态") {
      this.router.navigate(['/monitor/turbmatrix']);
    }
    

  }

}
export interface NameValue {
  value: number;
  name: string;
}
export class TurbstatusData {
  id: number;
  key: string;
  name: string;
  color: string;
  value: number;
}
export class TurbstatusTable {
  public rows: TurbstatusRow[] = [];
  public title: string[];
}
export class TurbstatusRow {
  public columns: TurbstatusColumn[] = [];
  public farmName: string;
}
export class TurbstatusColumn {
  constructor(
    public value: any,
    public color: string = null,
  ) {
  }
}




// WEBPACK FOOTER //
// ./src/app/module/monitor/main/turbstatus-panel/turbstatus-panel.component.ts